import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/device/gateway/add_gateway/wifi_page.dart";
import "package:ct_pa_majordomo/pages/device/gateway/add_gateway/widgets/list_item.dart";
import "package:ct_pa_majordomo/pages/device/gateway/api.dart";
import "package:ct_pa_majordomo/router/keys.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";
import "package:permission_handler/permission_handler.dart";
import "package:ttlock_flutter/ttgateway.dart";
import "package:ttlock_flutter/ttlock.dart";

class AddGateway extends StatefulWidget {
  const AddGateway({super.key});

  @override
  State<StatefulWidget> createState() => _AddGatewayState();
  
}

class _AddGatewayState extends State<AddGateway> {
//   TTGatewayScanModel({
//   "gatewayName": "like",
//   "gatewayMac": "2001-5523-6354-2365-12",
//   "rssi": -60,
//   "type": 1,
//   "isDfuMode": false,
// }),
  List<TTGatewayScanModel> _gatewayList = [];
  bool _isScanning = false;

  // 检查蓝牙权限
  Future<bool> _checkBluetoothPermission() async {
    PermissionStatus status = await Permission.bluetoothConnect.status;
    if (status.isGranted) {
      return true;
    } else {
      PermissionStatus permission = await Permission.bluetoothConnect.request();
      if (permission.isGranted) {
        return true;
      } else {
        if (mounted) {
          EasyLoading.showToast("请前往权限中心手动授权蓝牙权限");
        }
        return false;
      }
    }
  }

  // 开始扫描网关
  void _startScanGateway() async {
    if (_isScanning) return;
    
    bool hasPermission = await _checkBluetoothPermission();
    if (!hasPermission) return;

    setState(() {
      _isScanning = true;
      _gatewayList = [];
    });

    TTGateway.startScan((scanModel) {
      print("网关：>>>$scanModel");
      bool contain = false;
      for (TTGatewayScanModel model in _gatewayList) {
        if (scanModel.gatewayMac == model.gatewayMac) {
          contain = true;
          break;
        }
      }
      if (!contain) {
        setState(() {
          _gatewayList.add(scanModel);
        });
      }
    });
  }

  // 停止扫描
  void _stopScanGateway() {
    TTGateway.stopScan();
    setState(() {
      _isScanning = false;
    });
  }

  @override
  void initState() {
    super.initState();
    TTLock.printLog = true;
    // 进入页面时自动检测权限并开始扫描
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _startScanGateway();
    });
  }

  @override
  void dispose() {
    _stopScanGateway();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        iconTheme: const IconThemeData(color: Colors.white),
        title: const Text("添加网关", style: TextStyle(color: Colors.white),),
        centerTitle: true,
        backgroundColor: ThemeVars.colorPrimary,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios_new),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
        actions: [
          IconButton(
            onPressed: () {
              if (_isScanning) {
                _stopScanGateway();
                // 停止扫描后延迟一下再重新开始扫描
                Future.delayed(const Duration(milliseconds: 500), () {
                  if (mounted) {
                    _startScanGateway();
                  }
                });
              } else {
                _startScanGateway();
              }
            },
            icon: const Icon(Icons.add),
          ),
        ],
      ),
      body: ListView(
        padding: const EdgeInsets.all(ThemeVars.paddingPage),
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              const Text("附近的网关", style: TextStyle(fontSize: 13, color: ThemeVars.colorTextTer),),
              if (_isScanning)
                const Row(
                  children: [
                    SizedBox(
                      width: 12,
                      height: 12,
                      child: CircularProgressIndicator(
                        strokeWidth: 2,
                        valueColor: AlwaysStoppedAnimation<Color>(ThemeVars.colorPrimary),
                      ),
                    ),
                    SizedBox(width: 8),
                    Text("扫描中...", style: TextStyle(fontSize: 12, color: ThemeVars.colorTextTer)),
                  ],
                ),
            ],
          ),
          const SizedBox(height: 10,),
          GestureDetector(
            onTap: () async {
              PermissionStatus status = await Permission.bluetoothConnect.status;
              print("status:>>>$status");
              if (status.isGranted) {
                Stacker.pushNamed(Keys.DEVICE_GATEWAY_SELECT_WIFI);
              } else {
                PermissionStatus permission = await Permission.bluetoothConnect.request();
                if (permission.isGranted) {
                  if (context.mounted) {
                    Stacker.pushNamed(Keys.DEVICE_GATEWAY_SELECT_WIFI);
                  }
                } else {
                  EasyLoading.showToast("请前往权限中心手动授权");
                }
              }
            },
            child: Text("选择wifi"),
          ),
          const SizedBox(height: 20,),
          // 网关列表
          if (_gatewayList.isEmpty && !_isScanning)
            // 暂无数据提示
            Container(
              padding: const EdgeInsets.symmetric(vertical: 60),
              child: Column(
                children: [
                  Icon(
                    Icons.bluetooth_searching,
                    size: 64,
                    color: Colors.grey[400],
                  ),
                  const SizedBox(height: 16),
                  Text(
                    "暂无发现网关设备",
                    style: TextStyle(
                      fontSize: 16,
                      color: Colors.grey[600],
                    ),
                  ),
                  const SizedBox(height: 8),
                  Text(
                    "请确保网关设备已开启并处于可发现状态",
                    style: TextStyle(
                      fontSize: 14,
                      color: Colors.grey[500],
                    ),
                    textAlign: TextAlign.center,
                  ),
                  const SizedBox(height: 20),
                  ElevatedButton(
                    onPressed: _startScanGateway,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: ThemeVars.colorPrimary,
                      foregroundColor: Colors.white,
                    ),
                    child: const Text("重新扫描"),
                  ),
                ],
              ),
            )
          else
            Column(
              children: _gatewayList.map((ele) {
                return Padding(
                  padding: const EdgeInsets.only(bottom: 12),
                  child: ListItem(gateway: ele,),
                );
              }).toList(),
            ),
        ],
      ),
    );
  }
}